﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Data;
using System.Data.SqlClient;

namespace ASBCC.WebCache
{
    public class SqlDependencyWebCache : WebCacheBase
    {
        private string _connectionString;

        private SqlConnection GetConnection()
        {
            return new SqlConnection(this._connectionString);
        }

        private SqlCommand GetSelectCommand(string key)
        {
            SqlConnection conn = this.GetConnection();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp3_CheckCacheDependency";
            SqlParameter sqlParam = cmd.Parameters.Add("@CacheKey", SqlDbType.VarChar, 100);
            sqlParam.Value = key;
            return cmd;
        }

        private SqlCommand GetUpdateCommand(string key)
        {
            SqlConnection conn = this.GetConnection();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "usp3_UpdateCacheDependency";
            SqlParameter sqlParam = cmd.Parameters.Add("@CacheKey", SqlDbType.VarChar, 100);
            sqlParam.Value = key;
            return cmd;
        }

        private void UpdateCacheDependency(string key)
        {
            SqlCommand cmd = this.GetUpdateCommand(key);
            using (cmd.Connection)
            {
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
            }
        }

        protected override void OnBeforeAdd(string key)
        {
            this.UpdateCacheDependency(key);
        }

        protected override CacheDependency GetCacheDependency(string key)
        {
            SqlCommand cmd = this.GetSelectCommand(key);
            SqlCacheDependency sqlCacheDependency = new SqlCacheDependency(cmd);
            using (cmd.Connection)
            {
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
            }
            return sqlCacheDependency;
        }

        public SqlDependencyWebCache(string connectionString)
        {
            this._connectionString = connectionString;
        }

        public override void Remove(string key, bool useDependency)
        {
            if (!this.CheckParameters(key)) return;
            if (useDependency)
            {
                this.UpdateCacheDependency(key);
            }
            else
            {
                base.Remove(key, useDependency);
            }
        }
    }
}
